<template>
  <div class="sms-login-view">
    <div class="login-container">
      <!-- 左侧背景区域，与普通登录保持一致 -->
      <div class="login-left">
        <div class="left-content">
          <div class="stats-cards">
            <div class="stat-card income">
              <div class="card-label">创业基金</div>
              <div class="card-value">¥40,832.32</div>
              <div class="card-change">13.8% <span class="up">↑</span> 较上月增长</div>
            </div>
            <div class="stat-card platform">
              <div class="stat-title">项目展示</div>
              <div class="stat-value">3259</div>
              <div class="stat-change">6.22% <span class="up">↑</span> 较上月增长</div>
            </div>
            <div class="stat-card platform">
              <div class="stat-title">新增创业团队</div>
              <div class="stat-value">218</div>
              <div class="stat-change">8.9% <span class="up">↑</span> 较上月增长</div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 右侧登录表单区域 -->
      <div class="login-right">
        <el-form :model="smsForm" class="login-form">
          <div class="logo-title-wrapper">
            <img src="@/assets/logo.png" alt="logo" class="logo" />
            <div class="title">创业灯塔-齐学创"青年大学生创业生涯规划智慧云平台</div>
            <div class="subtitle">手机短信验证码登录</div>
          </div>
          <div class="form-content">
            <div class="form-group" v-if="userList.length>1">
              <label class="form-label">用户类型：</label>
              <el-select v-model="smsForm.role" placeholder="请选择用户类型">
                <el-option 
                  v-for="(item,index) in userList" 
                  :key="index"
                  :label="item.roleName" 
                  :value="item.roleName"
                ></el-option>
              </el-select>
            </div>
            <div class="form-group">
              <label class="form-label">手机号：</label>
              <input 
                class="form-input" 
                v-model="smsForm.mobile" 
                name="mobile" 
                placeholder="请输入手机号" 
              />
            </div>
            <div class="form-group verification-code">
              <label class="form-label">验证码：</label>
              <input 
                class="form-input code-input" 
                v-model="smsForm.code" 
                name="code" 
                placeholder="请输入验证码" 
              />
              <el-button 
                class="send-code-btn" 
                :disabled="countdown > 0" 
                @click="sendVerificationCode"
              >
                {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
              </el-button>
            </div>
            <div class="login-wrapper">
              <el-button class="login-btn" @click="handleSmsLogin">登录</el-button>
            </div>
            <div class="login-options">
              <span class="option-link" @click="switchToPasswordLogin">密码登录</span>
              <span class="option-separator">|</span>
              <span class="option-link" @click="handleRegister">注册账号</span>
            </div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted, onUnmounted } from "vue";
import { useStore } from 'vuex';
import { useRouter } from 'vue-router';
import menu from '@/utils/menu';
import { ElMessageBox, ElMessage } from 'element-plus'

const store = useStore();
const router = useRouter();
const context = getCurrentInstance()?.appContext.config.globalProperties;

// 用户类型列表
const userList = ref([]);
const menus = ref([]);

// 表单数据
const smsForm = ref({
  role: '',
  mobile: '',
  code: ''
});

const tableName = ref('');
const countdown = ref(0);
const loading = ref(false); // 添加loading变量
let timer = null;

// 发送验证码
const sendVerificationCode = async () => {
  // 验证手机号
  const mobilePattern = /^1[3-9]\d{9}$/;
  if (!smsForm.value.mobile || !mobilePattern.test(smsForm.value.mobile)) {
    context?.$toolUtil.message('请输入正确的手机号', 'error');
    return;
  }

  // 获取用户类型对应的表名
  if (userList.value.length > 1) {
    if (!smsForm.value.role) {
      context?.$toolUtil.message('请选择用户类型', 'error');
      return;
    }
    for (let i = 0; i < menus.value.length; i++) {
      if (menus.value[i].roleName == smsForm.value.role) {
        tableName.value = menus.value[i].pathName || menus.value[i].tableName;
      }
    }
  } else {
    tableName.value = userList.value[0].pathName || userList.value[0].tableName;
    smsForm.value.role = userList.value[0].roleName;
  }

  try {
    const res = await context?.$http({
      url: '/common/sendLoginSmsCode',
      method: 'get',
      params: {
        mobile: smsForm.value.mobile,
        loginType: 'front'
      }
    });
    
    if (res.data.code === 0) {
      context?.$toolUtil.message('验证码发送成功，请注意查收', 'success');
      countdown.value = 60;
      clearInterval(timer);
      timer = setInterval(() => {
        countdown.value--;
        if (countdown.value <= 0) {
          clearInterval(timer);
        }
      }, 1000);
    } else {
      context?.$toolUtil.message(res.data.msg || '验证码发送失败', 'error');
    }
  } catch (error) {
    context?.$toolUtil.message(error.message || '验证码发送失败', 'error');
  }
};

// 登录提交
const handleSmsLogin = async () => {
  // 表单验证
  if (!smsForm.value.mobile) {
    context?.$toolUtil.message('请输入手机号', 'error');
    return;
  }
  if (!smsForm.value.code) {
    context?.$toolUtil.message('请输入验证码', 'error');
    return;
  }

  // 获取用户类型对应的表名
  if (userList.value.length > 1) {
    if (!smsForm.value.role) {
      context?.$toolUtil.message('请选择用户类型', 'error');
      return;
    }
    for (let i = 0; i < menus.value.length; i++) {
      if (menus.value[i].roleName == smsForm.value.role) {
        tableName.value = menus.value[i].pathName || menus.value[i].tableName;
      }
    }
  } else {
    tableName.value = userList.value[0].pathName || userList.value[0].tableName;
    smsForm.value.role = userList.value[0].roleName;
  }

  try {
    loading.value = true
    const response = await context?.$http({
      url: '/common/smsLogin',
      method: 'get',
      params: {
        phone: smsForm.value.mobile,
        code: smsForm.value.code,
        loginType: 'front'
      }
    })
    
    console.log('登录响应:', response);
    
    if (response.data.code === 0) {
      // 直接处理登录成功
      handleLoginSuccess(response.data)
    } else if (response.data.code === 1 && response.data.roles && response.data.roles.length > 1) {
      // 显示角色选择对话框
      const role = await showRoleSelectionDialog(response.data.roles)
      if (role) {
        // 使用选定的角色重新登录
        loading.value = true
        const roleResponse = await context?.$http({
          url: '/common/smsLogin',
          method: 'get',
          params: {
            phone: smsForm.value.mobile,
            code: smsForm.value.code,
            role: role,
            loginType: 'front'
          }
        })
        if (roleResponse.data.code === 0) {
          handleLoginSuccess(roleResponse.data)
        } else {
          loading.value = false
          ElMessage.error(roleResponse.data.msg || '登录失败')
        }
      } else {
        loading.value = false
        ElMessage.warning('登录已取消')
      }
    } else {
      loading.value = false
      ElMessage.error(response.data.msg || '登录失败')
    }
  } catch (error) {
    loading.value = false
    console.error('登录失败:', error)
    ElMessage.error('登录失败，请稍后重试')
  }
};

// 处理登录成功
const handleLoginSuccess = (response) => {
  context?.$toolUtil.storageSet("frontToken", response.token);
  context?.$toolUtil.storageSet("frontRole", response.role || smsForm.value.role);
  context?.$toolUtil.storageSet("frontSessionTable", response.tableName || tableName.value);
  store.dispatch('user/getSession');

  let path = context?.$toolUtil.storageGet('toPath');
  if (path && path != '/login' && path != '/smsLogin') {
    router.push(path);
    context?.$toolUtil.storageRemove('toPath');
    return;
  }
  
  router.push('/index/home');
};

// 检查用户在系统中的角色
const checkSmsUserRoles = async (mobile) => {
  try {
    // 检查创业者表
    let roles = []
    
    try {
      const chuangyezheResponse = await context?.$http({
        url: 'chuangyezhe/page',
        method: 'get',
        params: {
          page: 1,
          limit: 1,
          shoujihaoma: mobile
        }
      });
      
      if (chuangyezheResponse.code === 0 && chuangyezheResponse.data.list.length > 0) {
        roles.push("创业者")
      }
    } catch (error) {
      console.error('检查创业者角色失败:', error)
    }
    
    // 检查导师表
    try {
      const daoshiResponse = await context?.$http({
        url: 'daoshi/page',
        method: 'get',
        params: {
          page: 1,
          limit: 1,
          shoujihaoma: mobile
        }
      });
      
      if (daoshiResponse.code === 0 && daoshiResponse.data.list.length > 0) {
        roles.push("导师")
      }
    } catch (error) {
      console.error('检查导师角色失败:', error)
    }
    
    // 检查管理员表
    const adminTypes = [
      { role: "市级管理员", table: "shijiguanliyuan" },
      { role: "区级管理员", table: "qujiguanliyuan" },
      { role: "学校管理员", table: "xuexiaoguanliyuan" },
      { role: "街道管理员", table: "jiedaoguanliyuan" },
      { role: "学院管理员", table: "xueyuanguanliyuan" }
    ]
    
    for (const admin of adminTypes) {
      try {
        const adminResponse = await context?.$http({
          url: `${admin.table}/page`,
          method: 'get',
          params: {
            page: 1,
            limit: 1,
            shoujihaoma: mobile
          }
        });
        
        if (adminResponse.code === 0 && adminResponse.data.list.length > 0) {
          // 检查审核状态
          const user = adminResponse.data.list[0]
          if (user.sfsh === '是') {
            roles.push(admin.role)
          }
        }
      } catch (error) {
        console.error(`检查${admin.role}角色失败:`, error)
      }
    }
    
    return { roles }
  } catch (error) {
    console.error('检查用户角色失败:', error)
    return { roles: [] }
  }
};

// 显示角色选择对话框
const showRoleSelectionDialog = (roles) => {
  return new Promise((resolve) => {
    ElMessageBox.prompt(
      '您的手机号关联多个角色，请选择登录身份',
      '选择登录角色',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        inputPlaceholder: '请选择登录角色',
        inputType: 'select',
        inputValue: roles[0],
        inputOptions: roles.map(role => ({ label: role, value: role }))
      }
    )
      .then(({ value }) => {
        resolve(value)
      })
      .catch(() => {
        resolve(null)
      })
  })
};

// 切换到密码登录
const switchToPasswordLogin = () => {
  router.push('/login');
};

// 注册
const handleRegister = () => {
  if (!smsForm.value.role && userList.value.length > 1) {
    context?.$toolUtil.message('请先选择用户类型', 'error');
    return;
  }
  
  const role = smsForm.value.role || userList.value[0].roleName;
  let registerPath = '';
  
  if (role === '创业者') {
    registerPath = '/chuangyezheRegister';
  } else if (role === '导师') {
    registerPath = '/daoshiRegister';
  } else {
    context?.$toolUtil.message('当前用户类型不支持注册', 'error');
    return;
  }
  
  router.push(registerPath);
};

// 获取菜单
const getMenu = async () => {
  let arr = menu.list();
  if (!arr) {
    let res = await context?.$http.get("menu/list");
    context?.$toolUtil.storageSet("menus", res.data.data.list[0].menujson);
    arr = JSON.parse(res.data.data.list[0].menujson);
  }
  menus.value = arr;
  
  // 筛选支持前端登录的用户类型，且只保留创业者和导师
  userList.value = menus.value.filter(item => 
    item.hasFrontLogin === '是' && 
    (item.tableName === 'chuangyezhe' || item.tableName === 'daoshi')
  );
};

// 初始化
const init = async () => {
  await getMenu();
  if (userList.value.length > 0) {
    smsForm.value.role = userList.value[0].roleName;
  }
};

onMounted(() => {
  init();
});

onUnmounted(() => {
  // 清除定时器
  if (timer) {
    clearInterval(timer);
    timer = null;
  }
});
</script>

<style lang="scss" scoped>
.sms-login-view {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f5f5;
  padding: 0;
}

.login-container {
  display: flex;
  width: 1000px;
  height: 600px;
  background: #fff;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 10px 20px rgba(0,0,0,0.1);
}

.login-left {
  width: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  color: white;
}

.left-content {
  max-width: 420px;
  margin: 0 auto;
}

.stats-cards {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.stat-card {
  background: rgba(255,255,255,0.1);
  backdrop-filter: blur(10px);
  border-radius: 10px;
  padding: 20px;
}

.card-label {
  font-size: 14px;
  opacity: 0.8;
  margin-bottom: 5px;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 10px;
}

.card-change, .stat-change {
  font-size: 12px;
  opacity: 0.8;
}

.stat-title {
  font-size: 16px;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 5px;
}

.up {
  color: #00ff9d;
}

.login-right {
  width: 50%;
  padding: 40px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.login-form {
  width: 100%;
  max-width: 320px;
  margin: 0 auto;
}

.logo-title-wrapper {
  text-align: center;
  margin-bottom: 30px;
}

.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 15px;
}

.title {
  color: #333;
  font-size: 16px;
  margin-bottom: 5px;
  font-weight: bold;
}

.subtitle {
  color: #666;
  font-size: 14px;
  margin-bottom: 20px;
}

.form-content {
  margin-top: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
}

.form-input {
  width: 100%;
  height: 40px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 15px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-input:focus {
  border-color: #667eea;
  outline: none;
}

.verification-code {
  display: flex;
  flex-direction: column;
}

.code-input {
  margin-bottom: 10px;
}

.send-code-btn {
  height: 40px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background 0.3s;
}

.send-code-btn:hover:not(:disabled) {
  background: #5a6fd1;
}

.send-code-btn:disabled {
  background: #a0aec0;
  cursor: not-allowed;
}

.login-wrapper {
  margin-top: 30px;
}

.login-btn {
  width: 100%;
  height: 40px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.3s;
}

.login-btn:hover {
  background: #5a6fd1;
}

.login-options {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.option-link {
  color: #667eea;
  cursor: pointer;
  transition: color 0.3s;
}

.option-link:hover {
  color: #5a6fd1;
  text-decoration: underline;
}

.option-separator {
  margin: 0 10px;
  color: #ddd;
}

@media (max-width: 768px) {
  .login-container {
    flex-direction: column;
    width: 100%;
    height: auto;
  }

  .login-left, .login-right {
    width: 100%;
  }

  .login-left {
    display: none;
  }
}
</style>